package com.camera2.http;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.camera2.local.SharedPrefer;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SendMessage {

    public static String voicePath = null;

    public static String send(Context context, String expertId, String userMessage) throws Exception {
        String TAG = "SendMessage";
        String message = null;
        String userId = SharedPrefer.Readid(context);
        Log.i(TAG, "send: id" + userId);
        File voicefile;
        if (voicePath == null) {
            File mFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/xiaomuyi");
            if (!mFile.exists()) {
                mFile.mkdir();
            }
            voicefile = new File(mFile + "/" + "voice.txt");

            byte[] sb = "voice".getBytes();
            FileOutputStream fos = new FileOutputStream(voicefile,true);
            fos.write(sb);
            fos.close();
            voicePath = mFile + "/" + "voice.txt";
        } else
             voicefile = new File(voicePath);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("expertId", expertId)
                .addFormDataPart("userId", userId)
                .addFormDataPart("userMessage", userMessage)
                .addFormDataPart("userVoice", voicePath, RequestBody.create(MediaType.parse("image/png"), voicefile));

        MultipartBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(GlobalUrl.getMessageUrl())
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        Log.i(TAG, "send: result" + result);
        JSONObject jsonObj = new JSONObject(result);
        message = jsonObj.getString("msg");

        return message;
    }


}
